import { _decorator, Component, Node } from 'cc';
import { ecs } from 'db://oops-framework/libs/ecs/ECS';
import { ECSEntity } from 'db://oops-framework/libs/ecs/ECSEntity';
import { Login } from '../Login';
import { oops } from 'db://oops-framework/core/Oops';
import { smc } from '../../common/SingletonModuleComp';
import { LoginEvent } from '../LoginEvent';
import { Match } from '../../match/Match';
const { ccclass, property } = _decorator;

@ecs.register('LoginNet')
export class LoginNetComp extends ecs.Comp {
    server:string = '';
    username: string = '';
    password: string = '';
    reset() { }
}


export class LoginNetSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    filter(): ecs.IMatcher {
        return ecs.allOf(LoginNetComp);
    }
    entityEnter(entity: Login): void {
        this.login(entity);
    }

    private async login(entity: Login) {
        let login = entity.get(LoginNetComp);

        // 设置本地存储独立用户标签
        oops.storage.setUser(login.username);

        // 请求登录
        let retLogin = await smc.net.hcGate.callApi(`Login`, {
            server: login.server,
            username: login.username,
            password: login.password
        });

        if (retLogin.isSucc) {
            let account = smc.account.AccountModel;
            account.uid = retLogin.res.uid;
            account.username = login.username;
            account.password = login.password;
            entity.remove(LoginNetComp);

            // 创建连接匹配服务器 Http 客户端
            smc.net.createHcMatch();

            // 进入匹配大厅
            this.enterMatch(entity);
        }
        else if (retLogin.err.code == "Exist_No_UserName") {
            this.register(entity);
        }
        else {
            oops.gui.toast("当前区在维护中");
            entity.remove(LoginNetComp);
        }
    }

    async register(e: Login) {
        let login = e.get(LoginNetComp);
        let retRegister = await smc.net.hcGate.callApi("Register", {
            username: login.username,
            password: login.password
        });

        if (retRegister.isSucc) {
            this.login(e);
        }
        else {
            oops.gui.toast(retRegister.err.message);
            e.remove(LoginNetComp);
        }
    }

    enterMatch(entity: Login) {
        oops.message.dispatchEvent(LoginEvent.Logined);
        entity.destroy();
        ecs.getEntity<Match>(Match);
    }

}


